package com.ebase.sys.service;


import com.ebase.sys.model.Role;
import com.ebase.sys.model.UserRole;
import com.ebase.sys.provider.AdminService;
import com.ebase.sys.mapper.master.RoleMapper;
import com.ebase.sys.mapper.master.UserRoleMapper;
import com.ebase.sys.mapper.read.ReadUserMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("adminService")
public class AdminServiceImpl implements AdminService {

    Logger log = Logger.getLogger(AdminServiceImpl.class);

    private final static String ADMIN_ROLE = "admin";

    @Autowired
    ReadUserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleMapper userRoleMapper;


    @Override
    public Integer getIsAdmin(Long userId) {
        log.info("调用my-soa-service-sys成功");
        return userMapper.findByRoleCount(userId, ADMIN_ROLE);
    }

    @Override
    public void setAdmin(Long userId, Integer isAdmin) {
        if (userId == 0) {
            return;
        }
        Role role = roleMapper.findByName(ADMIN_ROLE);
        UserRole userRole = userRoleMapper.findByUIdAndRId(userId, role.getId());
        if (isAdmin != null && isAdmin == 1) {
            if (userRole == null) {
                userRole = new UserRole();
                userRole.setuId(userId);
                userRole.setrId(role.getId());
                userRoleMapper.insert(userRole);
            }
        } else {
            if (userRole != null) {
                userRoleMapper.deleteByUIdAndRId(userId, role.getId());
            }
        }
    }
}
